/**
 * 解压一刻应用 - 资源下载脚本
 *
 * 此脚本将帮助您自动下载应用所需的所有图像和音频资源
 * 使用方法：在Node.js环境中运行此脚本
 *
 * 执行前请确保已安装所需的依赖：
 * npm install axios fs-extra
 */

const axios = require("axios");
const fs = require("fs-extra");
const path = require("path");

// 资源链接配置
const resources = {
  images: [
    {
      url: "https://example.com/avatar.png",
      path: "assets/avatar.png",
      name: "用户头像",
    },
    {
      url: "https://example.com/flappy-icon.png",
      path: "assets/flappy-icon.png",
      name: "像素小鸟图标",
    },
    {
      url: "https://example.com/knife-icon.png",
      path: "assets/knife-icon.png",
      name: "飞刀结界图标",
    },
    {
      url: "https://example.com/bubble-icon.png",
      path: "assets/bubble-icon.png",
      name: "拟物泡泡纸图标",
    },
    {
      url: "https://example.com/sand-icon.png",
      path: "assets/sand-icon.png",
      name: "动态沙画板图标",
    },
  ],
  sounds: [
    {
      url: "https://example.com/sounds/rain.mp3",
      path: "assets/sounds/rain.mp3",
      name: "雨声",
    },
    {
      url: "https://example.com/sounds/forest.mp3",
      path: "assets/sounds/forest.mp3",
      name: "森林",
    },
    {
      url: "https://example.com/sounds/fire.mp3",
      path: "assets/sounds/fire.mp3",
      name: "篝火",
    },
    {
      url: "https://example.com/sounds/ocean.mp3",
      path: "assets/sounds/ocean.mp3",
      name: "海洋",
    },
  ],
};

// 创建必要的目录
async function createDirectories() {
  await fs.ensureDir("assets");
  await fs.ensureDir("assets/sounds");
  console.log("✅ 目录创建成功");
}

// 下载单个文件
async function downloadFile(url, filePath, name) {
  try {
    const response = await axios({
      method: "GET",
      url: url,
      responseType: "stream",
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
      },
    });

    const writer = fs.createWriteStream(filePath);
    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
      writer.on("finish", () => {
        console.log(`✅ 下载成功: ${name}`);
        resolve();
      });
      writer.on("error", (err) => {
        console.error(`❌ 下载失败: ${name}`, err);
        reject(err);
      });
    });
  } catch (error) {
    console.error(`❌ 下载失败: ${name}`, error.message);
    throw error;
  }
}

// 下载所有资源
async function downloadAllResources() {
  try {
    await createDirectories();

    console.log("📥 开始下载图像资源...");
    for (const image of resources.images) {
      await downloadFile(image.url, image.path, image.name);
    }

    console.log("📥 开始下载音频资源...");
    for (const sound of resources.sounds) {
      await downloadFile(sound.url, sound.path, sound.name);
    }

    console.log("✨ 所有资源下载完成!");
    console.log("现在您可以打开 index.html 使用应用了。");
  } catch (error) {
    console.error("❌ 下载过程中发生错误:", error);
  }
}

// 执行下载
downloadAllResources();
